package org.chengn.level_easy.context706;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * @author GengMY
 * @date 2024/4/15
 * @Description 设计哈希映射
 */
public class Context706 {
    final int size = 1 << 7;
    List<Entry>[] list = new List[size];
    public Context706() {
    }

    public void put(int key, int value) {
        int idx = key % size;
        if (list[idx] == null) {
            list[idx] = new LinkedList<>();
        }
        for (int i = 0; i < list[idx].size(); ++i) {
            Entry entry = list[idx].get(i);
            if (entry.key == key) {
                entry.value = value;
                return;
            }
        }

        list[idx].add(new Entry(key, value));
    }

    public int get(int key) {
        int idx = key % size;
        if (list[idx] == null) {
            return -1;
        }
        for (int i = 0; i < list[idx].size(); ++i) {
            Entry entry = list[idx].get(i);
            if (entry.key == key) {
                return entry.value;
            }
        }
        return -1;
    }

    public void remove(int key) {
        int idx = key % size;
        if (list[idx] == null) {
            return;
        }
        Iterator itor = list[idx].iterator();
        while (itor.hasNext()) {
            Entry entry = (Entry)itor.next();
            if (entry.key == key) {
                itor.remove();
                return;
            }
        }
    }

    static class Entry {
        public int key;
        public int value;

        public Entry(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }
}
